package com.tycmc.util;

import redis.clients.jedis.*;

import java.io.IOException;
import java.util.*;

public class RedisUtil {
    //Redis服务器IP
    //private static final String ADDR = "192.168.30.101:26379";
    private static final String ADDR = "192.168.88.211:26379";
    //访问密码
    private static final String AUTH = "tykj66TYKJ";
    //sentinel名字
    private static final String SentinelName="master";
    //可用连接实例的最大数目，默认值为8；
    //如果赋值为-1，则表示不限制；如果pool已经分配了maxActive个jedis实例，则此时pool的状态为exhausted(耗尽)。
    private static final int MAX_ACTIVE = 1024;

    //控制一个pool最多有多少个状态为idle(空闲的)的jedis实例，默认值也是8。
    private static final int MAX_IDLE = 200;

    //等待可用连接的最大时间，单位毫秒，默认值为-1，表示永不超时。如果超过等待时间，则直接抛出JedisConnectionException；
    private static final int MAX_WAIT = 10000;

    private static final int TIMEOUT = 10000;

    //在borrow一个jedis实例时，是否提前进行validate操作；如果为true，则得到的jedis实例均是可用的；
    private static final boolean TEST_ON_BORROW = true;

    private static  JedisSentinelPool jedisSentinelPool=null;
    private static int database=5;

    /**
     * 初始化Redis连接池
     */
    static {
        try {
            Set<String> sentinels = new HashSet<String>();
            sentinels.add(ADDR);
            JedisPoolConfig poolConfig = new JedisPoolConfig();
            poolConfig.setMaxIdle(MAX_IDLE);
            poolConfig.setMaxWaitMillis(MAX_WAIT);
            poolConfig.setTestOnBorrow(TEST_ON_BORROW);
            jedisSentinelPool = new JedisSentinelPool(SentinelName, sentinels, poolConfig,TIMEOUT,AUTH,database);
            HostAndPort currentHostMaster = jedisSentinelPool.getCurrentHostMaster();
            System.out.println(currentHostMaster.getHost()+"--"+currentHostMaster.getPort());//获取主节点的信息
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取Jedis实例
     * @return
     */
    public synchronized static Jedis getJedis() {
        try {
            if (jedisSentinelPool != null) {
                return jedisSentinelPool.getResource();
            } else {
                Set<String> sentinels = new HashSet<String>();
                sentinels.add(ADDR);
                JedisPoolConfig poolConfig = new JedisPoolConfig();
                poolConfig.setMaxIdle(MAX_IDLE);
                poolConfig.setMaxWaitMillis(MAX_WAIT);
                poolConfig.setTestOnBorrow(TEST_ON_BORROW);
                jedisSentinelPool = new JedisSentinelPool(SentinelName, sentinels, poolConfig,TIMEOUT,AUTH,database);
                return  jedisSentinelPool.getResource();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 释放jedis资源
     * @param jedis
     */
    public static void returnResource(final Jedis jedis) {
        if (jedis != null) {
            jedis.close();
        }
    }

    public static void sadd(String key, Set<String> value) {
        Jedis jedis=null;
        try {
            jedis = getJedis();
            for(String str: value){
                jedis.sadd(key, str);
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }finally {
            if(jedis!=null){
                returnResource(jedis);
            }
        }
    }


    public static void set(String key, String value) {
        Jedis jedis=null;
        try {
            jedis = getJedis();
            jedis.set(key,value);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }finally {
            if(jedis!=null){
                returnResource(jedis);
            }
        }
    }


    public static void srem(String key, Set<String> value) {
        Jedis jedis=null;
        try {
            jedis = getJedis();
            Iterator<String> it = value.iterator();
            while(it.hasNext()){
                String str = it.next();
                jedis.srem(key, str);
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }finally {
            if(jedis!=null){
                returnResource(jedis);
            }
        }
    }


    public static String get(String key) {
        Jedis jedis=null;
        try {
            jedis = getJedis();
            return jedis.get(key);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }finally {
            if(jedis!=null){
                returnResource(jedis);
            }
        }
    }

    public static boolean exist(String key) {
        Jedis jedis=null;
        try {
            jedis = getJedis();
            return jedis.exists(key);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }finally {
            if(jedis!=null){
                returnResource(jedis);
            }
        }
    }

    public static Map<String,String> hgetAll(String key) {
        Jedis jedis=null;
        try {
            jedis = getJedis();
            return jedis.hgetAll(key);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }finally {
            if(jedis!=null){
                returnResource(jedis);
            }
        }
    }


    public static Long scard(String key) {
        Jedis jedis=null;
        try {
            jedis = getJedis();
            return jedis.scard(key);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }finally {
            if(jedis!=null){
                returnResource(jedis);
            }
        }
    }


    public static Set<String> smembers(String key) {
        Jedis jedis=null;
        try {
            jedis = getJedis();
            return jedis.smembers(key);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }finally {
            if(jedis!=null){
                returnResource(jedis);
            }
        }
    }


    public static boolean sismember(String key, String value) {
        Jedis jedis=null;
        try {
            jedis = getJedis();
            return jedis.sismember(key,value);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }finally {
            if(jedis!=null){
                returnResource(jedis);
            }
        }
    }


    public static String srandmember(String key) {
        Jedis jedis=null;
        try {
            jedis = getJedis();
            return jedis.srandmember(key);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }finally {
            if(jedis!=null){
                returnResource(jedis);
            }
        }
    }


    public static void hmset(String key, Map<String, String> map) {
        Jedis jedis=null;
        try {
            jedis = getJedis();
            jedis.hmset(key,map);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }finally {
            if(jedis!=null){
                returnResource(jedis);
            }
        }
    }


    public static Long hlen(String key) {
        Jedis jedis=null;
        try {
            jedis = getJedis();
            return jedis.hlen(key);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }finally {
            if(jedis!=null){
                returnResource(jedis);
            }
        }
    }


    public static Set<String> hkeys(String key) {
        Jedis jedis=null;
        try {
            jedis = getJedis();
            return jedis.hkeys(key);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }finally {
            if(jedis!=null){
                returnResource(jedis);
            }
        }
    }


    public static List<String> hvals(String key) {
        Jedis jedis=null;
        try {
            jedis = getJedis();
            return jedis.hvals(key);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }finally {
            if(jedis!=null){
                returnResource(jedis);
            }
        }
    }


    public static List<String> hmget(String key, String s1, String s2) {
        Jedis jedis=null;
        try {
            jedis = getJedis();
            return jedis.hmget(key,s1,s2);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }finally {
            if(jedis!=null){
                returnResource(jedis);
            }
        }
    }
    public static List<String> hmget(String key, String []str) {
        Jedis jedis=null;
        try {
            jedis = getJedis();
            return jedis.hmget(key,str);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }finally {
            if(jedis!=null){
                returnResource(jedis);
            }
        }
    }

    public static void hdel(String key, String s) {
        Jedis jedis=null;
        try {
            jedis = getJedis();
            jedis.hdel(key,s);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }finally {
            if(jedis!=null){
                returnResource(jedis);
            }
        }
    }


    public static void lpush(String key, List<String> list) {
        try {
            Jedis jedis = getJedis();
            for(String s: list){
                jedis.lpush(key,s);
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }


    public static List<String> lrange(String key, Long start, Long end) {
        Jedis jedis=null;
        try {
            jedis = getJedis();
            return jedis.lrange(key, start, end);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }finally {
            if(jedis!=null){
                returnResource(jedis);
            }
        }
    }


    public static void del(String key) {
        Jedis jedis=null;
        try {
            jedis = getJedis();
            jedis.del(key);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(jedis!=null){
                returnResource(jedis);
            }
        }
    }


    public static void append(String key, String value) {
        Jedis jedis=null;
        try {
            jedis = getJedis();
            jedis.append(key,value);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(jedis!=null){
                returnResource(jedis);
            }
        }
    }
    public static String hget(String filed, String key) {
        Jedis jedis=null;
        try {
            jedis = getJedis();
            return jedis.hget(filed, key);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(jedis!=null){
                returnResource(jedis);
            }
        }
        return null;
    }
    public static long hset(String key, String filed,String value) {
        Jedis jedis=null;
        try {
            jedis = getJedis();
            return jedis.hset(key, filed,value);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(jedis!=null){
                returnResource(jedis);
            }
        }
        return 0L;
    }
    //管道技术保存
    public static void hsetWithpip(String redisKey,Map<String,Object>map){
        Jedis jedis = getJedis();
        Pipeline pip = jedis.pipelined();
        pip.multi();//开启事务
        for(Map.Entry<String,Object>mapResult:map.entrySet()){
            pip.hset(redisKey,mapResult.getKey(),String.valueOf(mapResult.getValue()));
        }
        Response<List<Object>>txresult=pip.exec();//提交事务
        pip.sync();// 调用syn会关闭管道，所以在调用syn之后就不可以在使用管道了
       returnResource(jedis);
    }
    //管道技术获取
    public static List<Object> hgetWithpip(String redisKey,String ...fileds){
        Jedis jedis = getJedis();
        Pipeline pip = jedis.pipelined();
        pip.multi();//开启事务
        for(String key:fileds){
            pip.hget(redisKey,key);
        }
        Response<List<Object>>txresult=pip.exec();//提交事务
        pip.sync();// 调用syn会关闭管道，所以在调用syn之后就不可以在使用管道了
         List<Object>responses=txresult.get();
        if(responses==null||responses.isEmpty()){
            throw new RuntimeException("Pipeline error:no response...");
        }

        /*for(Object resp:responses){
            System.out.println("Response:"+resp);
        }*/
        returnResource(jedis);
        return responses;
    }
    public static void main(String args[]){
         // System.out.println(hmget("NHL_EngineFLT_2313527",new String[]{"4_3603","18_1177","c"}));
       // System.out.println(String.valueOf(null));
        //hgetWithpip("NHL_EngineLastData_2313527","","MsgESL_EgnState","MsgESL_VclSpeed","aa");
        Map<String,String>map=new HashMap<String,String>();
        map.put("aa","1");
        map.put("bb","1");
        Jedis jedis = getJedis();
        Pipeline pip = jedis.pipelined();
        pip.multi();//开启事务
        for(int i=0;i<100000;i++){
            pip.hmset("123123123",map);
        }
        Response<List<Object>>txresult=pip.exec();//提交事务
        pip.sync();// 调用syn会关闭管道，所以在调用syn之后就不可以在使用管道了
        System.out.println("OK");
        Map<String,String>map1=new HashMap<String,String>();
        map1.put("aa","1");
        map1.put("bb","1");
        for(int i=0;i<100000;i++){
            hmset("123123123_copy",map1);
        }
        System.out.println("OK1");
    }
}
